package cn.itcast.service.impl;

import cn.itcast.entity.Category;
import cn.itcast.entity.Page;
import cn.itcast.exceptionHandler.CustomException;
import cn.itcast.mapper.ICategoryMapper;
import cn.itcast.mapper.IDishMapper;
import cn.itcast.mapper.ISetmealMapper;
import cn.itcast.service.ICategoryService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
@Service
public class CategoryServiceImpl implements ICategoryService {
  @Autowired(required = false)
  private ICategoryMapper categoryMapper;

  @Autowired(required = false)
  private IDishMapper dishMapper;

  @Autowired(required = false)
  private ISetmealMapper setmealMapper;
    /**
     * 查询页数据
     * @param pageNum 页码
     * @param pageSize 页大小
     * @return
     */
    @Override
    public Page<Category> findByPage(Integer pageNum, Integer pageSize) {
         PageHelper.startPage(pageNum, pageSize);
        List<Category> categories = categoryMapper.findAll();
        PageInfo<Category> pageInfo = new PageInfo<>(categories);
        return new Page<>(pageInfo.getList(),pageInfo.getTotal(),pageSize,pageNum);
    }

    /**
     * 插入数据
     *
     * @param category
     */
    @Override
    public void save(Category category) {
        categoryMapper.save(category);
    }

    /**
     * 删除数据
     *分类下有关联dish或者setmeal则删除失败，抛出自定义异常。
     * @param id
     */
    @Override
    public void delete(Long id) {
        int count = dishMapper.findCount(id);
        if (count >0){
            throw new CustomException("请先删除相关的菜品");
        }
         count = setmealMapper.findCount(id);
        if (count >0){
            throw new CustomException("请先删除相关的套餐");
        }
        categoryMapper.delete(id);
    }

    /**
     * 更新数据
     *
     * @param category
     */
    @Override
    public void update(Category category) {
        categoryMapper.update(category);
    }

    /**
     * 查询所有
     */
    @Override
    public List<Category> findAll() {
      return categoryMapper.findAll();
    }

    /**
     * 根据类型查询
     *
     * @param type
     */
    @Override
    public List<Category> list(Integer type) {
        return categoryMapper.list(type);
    }
}
